<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="dataForm" :model="temp" :rules="rules" class="searchform" inline label-width="80px">

        <el-form-item label="标题" prop="url">
          <el-input
            v-model="listQuery.title"
            class="filter-item"
            placeholder="中文名称"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item>
          <el-button v-waves class="filter-item" @click="handleFilter">
            {{ $t('table.search') }}
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" @click="handleFilterReset">
            {{$t('bs.reset')}}
          </el-button>
        </el-form-item>
      </el-form>

    </div>

    <div
      style="padding: 2%;background: #ffffff;box-shadow: 0px 15px 24px 0px rgba(101,175,255,0.08);border-radius: 10px;"
    >
      <!--      <div style="display: flex;flex-direction: row;padding-bottom: 24px">-->
      <!--        <div style="flex: 1;display: flex;align-items: center">-->
      <!--          <el-button-->
      <!--            class="filter-item"-->
      <!--            plain-->
      <!--            size="small"-->
      <!--            style="margin-left: 10px;"-->
      <!--            type="primary"-->
      <!--            @click="handleCreate"-->
      <!--          >-->
      <!--            添加-->
      <!--          </el-button>-->
      <!--          <el-button-->
      <!--            class="filter-item"-->
      <!--            plain-->
      <!--            size="small"-->
      <!--            style="margin-left: 10px;"-->
      <!--            type="primary"-->
      <!--            @click="handleDeleteAll"-->
      <!--          >-->
      <!--            {{$t('bs.batchDelete')}}-->
      <!--          </el-button>-->
      <!--        </div>-->
      <!--        <div style="flex: 1;display: flex;align-items: center;justify-content: flex-end">-->
      <!--          <el-popover-->
      <!--            v-model="tablesetvisible"-->
      <!--            placement="bottom-start"-->
      <!--            width="160"-->
      <!--          >-->
      <!--            <div class="setcheckbox">-->
      <!--              <el-checkbox v-model="checked" @change="checkall">全选/不选</el-checkbox>-->
      <!--              <el-checkbox v-for="(item,k) in fileds" :key="k" v-model="item.is_show" false-label="0" true-label="1">-->
      <!--                {{ item.title }}-->
      <!--              </el-checkbox>-->
      <!--            </div>-->
      <!--            <div slot="reference" class="hoverbutton">-->
      <!--              <img src="/static/table/fiter.png">-->
      <!--              <span style="margin-left: 8px;color: #666666">筛选</span>-->
      <!--            </div>-->
      <!--          </el-popover>-->
      <!--        </div>-->
      <!--      </div>-->
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column label="序号" width="55">
          <template slot-scope="{$index,row}">
            <span>{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          type="selection"
          width="55"
        />

        <el-table-column label="标题">
          <template slot-scope="{row}">
            {{ row.title }}
          </template>
        </el-table-column>
        <el-table-column label="时间" width="180">
          <template slot-scope="{row}">
            {{ row.add_time }}
          </template>
        </el-table-column>
        <!--        <el-table-column   label="提交人" width="100">-->
        <!--          <template slot-scope="{row}">-->
        <!--            {{ row.px }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width" width="100">
          <template slot-scope="{row,$index}">
            <el-button circle icon="el-icon-view" size="small" @click="handleUpdate(row)" />
            <!--            <el-popconfirm-->
            <!--              title="确定删除吗？"-->
            <!--              @confirm="handleDelete([row.id])"-->
            <!--            >-->
            <!--              <el-button-->
            <!--                slot="reference"-->
            <!--                circle-->
            <!--                icon="el-icon-delete"-->
            <!--                size="small"-->
            <!--                style="margin-left: 8px"-->
            <!--              />-->
            <!--            </el-popconfirm>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="listQuery.limit"
        :page.sync="listQuery.page_no"
        :total="total"
        @pagination="getList"
      />

    </div>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="800px">
      <div>
        <el-form ref="dataForm" :model="temp" :rules="rules" label-width="120px" style="padding-right:32px;min-width: 700px">
          <el-row :gutter="2">
            <el-col :span="24">
              <el-form-item label="标题" prop="title">
                <el-input v-model="temp.title" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="反馈内容" prop="content">
                <tinymce v-model="temp.content" :height="300" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createData, updateData, delData } from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import _ from 'lodash'
import Pagination from '@/components/Pagination'
import CyTreeSelect from '@/components/CyTreeSelect'
import Tinymce from '@/components/Tinymce/index.vue' // secondary package based on el-pagination

export default {
  name: 'SlComment',
  components: { Tinymce, CyTreeSelect, Pagination },
  directives: { waves },
  data() {
    return {
      checked: true,
      tablesetvisible: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      },
      queryMap: {},
      showReviewer: false,
      temp: {
        id: '', title: '', add_user_id: '', content: '', add_time: ''
      },
      fileds: {
        name: { filed: 'name', title: '中文名称', is_show: '1' },
        en_name: { filed: 'en_name', title: '英文名称', is_show: '1' },
        px: { filed: 'px', title: '排序', is_show: '1' }
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
       update: this.$t("bs.edit"),
        create: this.$t("bs.add")
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        content: [{ required: true, message: '内容不能为空', trigger: 'blur' }]
      },
      downloadLoading: false

    }
  },
  created() {
    Date.prototype.Format = function(formatStr) {
      var str = formatStr
      var Week = ['日', '一', '二', '三', '四', '五', '六']

      str = str.replace(/yyyy|YYYY/, this.getFullYear())
      str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100))

      str = str.replace(/MM/, this.getMonth() > 9 ? this.getMonth().toString() : '0' + (this.getMonth() + 1))
      str = str.replace(/M/g, this.getMonth())

      str = str.replace(/w|W/g, Week[this.getDay()])

      str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate())
      str = str.replace(/d|D/g, this.getDate())

      str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours())
      str = str.replace(/h|H/g, this.getHours())
      str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes())
      str = str.replace(/m/g, this.getMinutes())

      str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds())
      str = str.replace(/s|S/g, this.getSeconds())

      return str
    }
    this.getList()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    changeType(val) {
      if (val == 2) {
        this.rules = {
          inc_type: [{ required: true, message: '请选择类型', trigger: 'change' }]
        }
      } else {
        this.rules = {
          name: [{ required: true, message: '中文名称不能为空', trigger: 'blur' }],
          en_name: [{ required: true, message: '英文名称不能为空', trigger: 'blur' }],
          inc_type: [{ required: true, message: '请选择类型', trigger: 'blur' }]
        }
      }

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    addListVal() {
      this.temp.list_val.push({
        // value: '',
        label: ''
      })
    },
    emptyListVal() {
      this.temp.list_val = []
    },
    delListVal(key) {
      this.temp.list_val.splice(key, 1)
    },
    checkall(val) {
      let check = '1'
      if (!val) {
        check = '0'
      }
      const keys = Object.keys(this.fileds)
      keys.map((item) => {
        this.fileds[item].is_show = check
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery, 'sl_comment').then(response => {
        if (response.data && response.data.items) {
          this.list = response.data.items
          this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    handleFilterReset() {
      this.listQuery = {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      }
      this.getList()
    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)

      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          console.log('查询', listkeys[i], isNaN(listkeys[i]))
          let operator = '='
          let value = this.listQuery[listkeys[i]]
          if (!this.queryMap[listkeys[i]]) {
            if (isNaN(listkeys[i])) {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          } else {
            if (this.queryMap[listkeys[i]] == 'like') {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          }
        }
      }
      this.list = []
      this.listQuery['where'] = queryParma
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '', title: '', add_user_id: '', content: '', add_time: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      console.log('数据', this.$store.state)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const temp = _.cloneDeep(this.temp)
          temp.add_user_id = this.$store.state.user.user_id
          var date = new Date()
          temp.add_time = date.Format('yyyy-MM-dd HH:mm:ss')
          const data = {
            modelname: 'station_attr',
            add: temp
          }

          createData({ data: [data] }, 'sl_comment').then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      console.log('数据', this.$store.state)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const temp = _.cloneDeep(this.temp)
          temp.add_user_id = this.$store.state.user.user_id
          var date = new Date()
          temp.add_time = date.Format('yyyy-MM-dd HH:mm:ss')
          const data = {
            modelname: 'station_attr',
            add: temp
          }
          updateData({ data: [data] }, 'sl_comment').then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDeleteAll() {
      console.log('删除全部', this.multipleSelection)
      if (!this.multipleSelection || this.multipleSelection.length == 0) {
        this.$message.error('请选择需要删除的数据')
        return
      }
      this.$confirm('你确定删除这' + this.multipleSelection.length + '条数据么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        for (var i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].id)
        }
        this.handleDelete(ids)
      })
    },
    handleDelete(ids) {
      console.log('删除', ids)
      delData({ id: ids.join(',') }, 'sl_comment').then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style scoped="scoped" type="scss">
.pagination-container {
  padding: 0px;
  padding-bottom: 16px;
}

.hoverbutton {
  width: 70px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  border-radius: 3px;
}

.hoverbutton:hover {
  border: 1px solid #999999;
}

.setcheckbox .el-checkbox {
  margin-bottom: 10px;
}

.searchform .el-form-item {
  margin-bottom: 0px;
  min-width: 280px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
</style>

